import threading
import time
import traceback

import cv2
from py_base import tool
from src import predict, keytool, win32, enum

KEY_FRONT = 'up'
KEY_BACK = 'down'
KEY_LEFT = 'left'
KEY_RIGHT = 'right'


def frame(image, stime):
    lines, circles, drawing = predict.predict_test(image)
    posInfo = []
    overNum = {'line':0, 'shot':0}
    dealShot(lines, circles, posInfo, True, overNum)
    dealShot(lines, circles, posInfo, False, overNum)
    h, w = drawing.shape[:2]
    gap = 15
    x = 75
    y = 100
    dot = {'FRONT': [x, y], 'BACK': [x, y - gap*2], 'LEFT': [x-gap, y-gap], 'RIGHT': [x+gap, y-gap]}

    for key, value in dot.items():
        color = (0, 255, 0)
        if key in posInfo:
            color = (0, 0, 255)
        cv2.circle(drawing, [value[0], h - value[1]], 8, color, -1)

    cv2.waitKey(1)
    FPS_string = 'FPS  ' + str(int(1 / (time.time() - stime)))  # 写在画面上的字符串
    tool.putText(drawing, FPS_string, 1)

    # 偏移量
    tool.putText(drawing, f"line:{overNum['line']} shot:{overNum['shot']}", 3)
    cv2.imshow('drawing', drawing)

def do():
    global KEY_FRONT, KEY_BACK, KEY_LEFT, KEY_RIGHT
    hwnd = win32.find_windows(enum.setting['winName'])
    if not hwnd:
        raise Exception("找不到窗口")

    while True:

        if not enum.predicting:
            cv2.destroyAllWindows()
            return
        # keyMap = tool.getEnumStrArr('keyMap')
        # KEY_FRONT, KEY_BACK, KEY_LEFT, KEY_RIGHT = keyMap
        stime = time.time()

        image, hwnd = tool.get_screenshot(hwnd)
        frame(image, stime)





def begin():
    try:
        do()
    except Exception as e:
        enum.main_window.info.setText(str(e))
        enum.main_window.set_predict(False)
        print('str(Exception):\t', str(Exception))
        print('traceback.print_exc():')
        traceback.print_exc()
        print('traceback.format_exc():\n%s' % traceback.format_exc())


def dealShot(lines, circles, positionInfo, isShot, overNum):
    if len(lines) == 0:
        return

    if len(circles) == 0 and isShot:
        return

    x1, y1, x2, y2 = lines[0]

    if isShot:
        x, y = circles[0]
        gap = y - y2
        overNum['shot'] = gap
    else:
        gap = y2 - y1
        overNum['line'] = gap

    if abs(gap) < enum.setting['minGap']:
        return

    now = int(round(time.time() * 1000))

    # keying = False
    # if keyboard.is_pressed(KEY_BACK):
    #     keying = True
    #
    # if keyboard.is_pressed(KEY_FRONT):
    #     keying = True
    # keying = False

    if gap > 0: # 头下沉
        if isShot:
            pos = "FRONT"
            key = KEY_BACK
        else:
            pos = "LEFT"
            key = KEY_RIGHT
    else:
        if isShot:
            pos = "BACK"
            key = KEY_FRONT
        else:
            pos = "RIGHT"
            key = KEY_LEFT

    positionInfo.append(pos)
    if enum.setting['balanceTimeGap'] == 0:
        return

    lastTime = enum.last_front_press if isShot else enum.last_left_press
    if now - lastTime < enum.setting['balanceTimeGap']:
        return

    pressTime = 100
    if gap > 15:
        pressTime = 300

    if enum.predicting:
        threading.Thread(target=keytool.press, args=(key, pressTime)).start()
        print(f"pos[{pos}] press[{key}]")

    if isShot:
        enum.last_front_press = now
    else:
        enum.last_left_press = now